package com.hunan.api.catv.service.biz.mix;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hunan.api.catv.common.CacheName;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.ColumnEnum;
import com.hunan.api.catv.entity.po.MixRecommend;
import com.hunan.api.catv.entity.vo.*;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.activity.ActivityBiz;
import com.hunan.api.catv.service.biz.album.AlbumBiz;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.biz.live.LiveBiz;
import com.hunan.api.catv.service.biz.news.NewsBiz;
import com.hunan.api.catv.service.impl.mix.MixRecommendService;
import com.hunan.api.catv.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 混合推荐
 */
@CacheConfig(cacheNames = CacheName.recommend)
@Service
public class MixRecommendBiz extends ResultService {

    @Autowired
    MixRecommendService mixRecommendService;

    @Autowired
    MixRecommendBiz mixRecommendBiz;

    @Autowired
    NewsBiz newsBiz;

    @Autowired
    LiveBiz liveBiz;

    @Autowired
    AlbumBiz albumBiz;

    @Autowired
    ActivityBiz activityBiz;

    @Autowired
    CacheBiz cacheBiz;

    @Autowired
    RedisUtils redisUtils;

    public ServiceResult add(MixRecommend mixRecommend) {
        List<MixRecommendVo> list = mixRecommendBiz.list(mixRecommend.getContentType(), mixRecommend.getContentId());
        if (!list.isEmpty()) {
            return buildFail(ConstantsMsg.mix_add_fail);
        }
        ServiceResult serviceResult = mixRecommendService.add(mixRecommend);
        if (!serviceResult.getStatus()) {
            return buildFail(ConstantsMsg.admin_add_fail);
        }
        return serviceResult;
    }

    public ServiceResult edit(Integer recommendId, Integer state) {
        MixRecommend mixRecommend = new MixRecommend();
        mixRecommend.setRecommendId(recommendId);
        mixRecommend.setState(state);
        ServiceResult serviceResult = mixRecommendService.update(mixRecommend);
        if (!serviceResult.getStatus()) {

            return buildFail(ConstantsMsg.admin_edit_fail);
        }
        return serviceResult;
    }

    public ServiceResult edit(Integer recommendId, Boolean top) {
        MixRecommend mixRecommend = new MixRecommend();
        mixRecommend.setRecommendId(recommendId);
        mixRecommend.setIsTop(top);
        ServiceResult serviceResult = mixRecommendService.update(mixRecommend);
        if (!serviceResult.getStatus()) {
            return buildFail(ConstantsMsg.admin_edit_fail);
        }
        return serviceResult;
    }

    public ServiceResult del(Integer recommendId) {
        ServiceResult serviceResult = mixRecommendService.delete(recommendId);
        if (!serviceResult.getStatus()) {
            return buildFail(ConstantsMsg.admin_del_fail);
        }
        return serviceResult;
    }

    public List<MixRecommendVo> list(Integer contentType, Integer contentId) {
        MixRecommend mixRecommend = new MixRecommend();
        mixRecommend.setContentType(contentType);
        mixRecommend.setContentId(contentId);
        return mixRecommendService.list(mixRecommend);
    }

    public PageInfo<MixRecommendVo> adminList(Integer contentType, Integer state, Boolean isTop, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        MixRecommend mixRecommend = new MixRecommend();
        mixRecommend.setContentType(contentType);
        mixRecommend.setState(state);
        mixRecommend.setIsTop(isTop);
        List<MixRecommendVo> list = mixRecommendService.list(mixRecommend);
        for (int i = 0; i < list.size(); i++) {
            MixRecommendVo mixRecommendVo = list.get(i);
            ColumnEnum columnEnum = ColumnEnum.getResult(mixRecommendVo.getContentType());
            Integer contentId = mixRecommendVo.getContentId();
            switch (columnEnum) {
                case news:
                    NewsVo newsVo = newsBiz.info(contentId);
                    if (!ObjectUtils.isEmpty(newsVo)) {
                        mixRecommendVo.setTitle(newsVo.getTitle());
                        mixRecommendVo.setCover(newsVo.getPicMinivideo());
                    }
                    break;
                case video:
                    AlbumVo albumVo = albumBiz.info(contentId);
                    if (!ObjectUtils.isEmpty(albumVo)) {
                        mixRecommendVo.setTitle(albumVo.getName());
                        mixRecommendVo.setCover(albumVo.getCoverUrl());
                    }
                    break;
                case tv:
                    LiveVo tvLive = liveBiz.info(contentId);
                    if (!ObjectUtils.isEmpty(tvLive)) {
                        mixRecommendVo.setTitle(tvLive.getTitle());
                        mixRecommendVo.setCover(tvLive.getCover());
                    }
                    break;
                case live:
                    LiveVo liveLive = liveBiz.info(contentId);
                    if (!ObjectUtils.isEmpty(liveLive)) {
                        mixRecommendVo.setTitle(liveLive.getTitle());
                        mixRecommendVo.setCover(liveLive.getCover());
                    }
                    break;
                case activity:
                    ActivityVo activityVo = activityBiz.info(contentId);
                    if (!ObjectUtils.isEmpty(activityVo)) {
                        mixRecommendVo.setTitle(activityVo.getTitle());
                        mixRecommendVo.setCover(activityVo.getCover());
                    }
                    break;
                default:
                    break;
            }
        }
        return new PageInfo<MixRecommendVo>(list);
    }


    @Cacheable(unless = "#result == null")
    public List<Object> topList() {
        MixRecommend mixRecommend = new MixRecommend();
        mixRecommend.setIsTop(true);
        mixRecommend.setState(1);
        List<MixRecommendVo> list = mixRecommendService.list(mixRecommend);
        List<Object> topList = new LinkedList<>();
        for (MixRecommendVo mrv : list) {
            Integer id = mrv.getContentId();
            if (ColumnEnum.news.getCode().equals(mrv.getContentType())) {
                NewsVo newsVo = cacheBiz.newsInfo(id);
                if (!ObjectUtils.isEmpty(newsVo) && 1 == newsVo.getState()) {
                    topList.add(newsVo);
                }
            } else if (ColumnEnum.video.getCode().equals(mrv.getContentType())) {
                AlbumVo albumVo = cacheBiz.albumInfo(id);
                if (!ObjectUtils.isEmpty(albumVo) && 1 == albumVo.getState()) {
                    topList.add(albumVo);
                }
            } else if (ColumnEnum.activity.getCode().equals(mrv.getContentType())) {
                ActivityVo activityVo = cacheBiz.activityInfoCache(id);
                if (!ObjectUtils.isEmpty(activityVo) && 1 == activityVo.getState()) {
                    topList.add(activityVo);
                }
            } else if (ColumnEnum.live.getCode().equals(mrv.getContentType()) || ColumnEnum.tv.getCode().equals(mrv.getContentType())) {
                LiveVo liveVo = cacheBiz.liveInfo(id);
                if (!ObjectUtils.isEmpty(liveVo) && 1 == liveVo.getState()) {
                    topList.add(liveVo);
                }
            }
        }
        return topList;
    }

    @Cacheable(unless = "#result == null")
    public PageInfo<Object> page(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        MixRecommend mixRecommend = new MixRecommend();
        mixRecommend.setIsTop(false);
        mixRecommend.setState(1);
        List<MixRecommendVo> list = mixRecommendService.list(mixRecommend);
        List<Object> resultList = new LinkedList<>();
        for (MixRecommendVo mrv : list) {
            Integer id = mrv.getContentId();
            if (ColumnEnum.news.getCode().equals(mrv.getContentType())) {
                NewsVo newsVo = cacheBiz.newsInfo(id);
                if (!ObjectUtils.isEmpty(newsVo) && 1 == newsVo.getState()) {
                    resultList.add(newsVo);
                }
            } else if (ColumnEnum.video.getCode().equals(mrv.getContentType())) {
                AlbumVo albumVo = cacheBiz.albumInfo(id);
                if (!ObjectUtils.isEmpty(albumVo) && 1 == albumVo.getState()) {
                    resultList.add(albumVo);
                }
            } else if (ColumnEnum.activity.getCode().equals(mrv.getContentType())) {
                ActivityVo activityVo = cacheBiz.activityInfoCache(id);
                if (!ObjectUtils.isEmpty(activityVo) && 1 == activityVo.getState()) {
                    resultList.add(activityVo);
                }
            } else if (ColumnEnum.live.getCode().equals(mrv.getContentType()) || ColumnEnum.tv.getCode().equals(mrv.getContentType())) {
                LiveVo liveVo = cacheBiz.liveInfo(id);
                if (!ObjectUtils.isEmpty(liveVo) && 1 == liveVo.getState()) {
                    resultList.add(liveVo);
                }
            }
        }
        PageInfo<MixRecommendVo> MixRecommendList = new PageInfo<>(list);
        PageInfo<Object> objList = new PageInfo<>();
        BeanUtils.copyProperties(MixRecommendList, objList);
        objList.setList(resultList);
        return objList;
    }

    public void flushNewsCache(Integer newsId) {
        NewsVo newsVo = newsBiz.getById(newsId);
        if (!ObjectUtils.isEmpty(newsVo)) {
//			List<Object> topList = cacheBiz.recommendTopList();
            List<Object> topList = topList();
            topList.forEach(t -> {
                if (t instanceof NewsVo) {
                    NewsVo topNews = (NewsVo) t;
                    if (topNews.getNewsId().equals(newsId)) {
                        topNews = newsVo;
                    }
                }
            });
            String redisTopKey = "r::topList";
            redisUtils.set(redisTopKey, topList);
//			@SuppressWarnings("unchecked")
//			LoadingCache<Object,List<Object>> topBean = SpringBeanUtils.getBean("recommendTopListCache", LoadingCache.class);
//			topBean.put("recommendTopListCache", topList);
            Integer total = mixRecommendService.totalNum();
            Integer size = total / 20 + 1;
            Integer pageNum = 0;
            List<Object> newList = new ArrayList<Object>();
            PageInfo<Object> newPage = new PageInfo<Object>();
            for (int i = 1; i <= size; i++) {
                PageInfo<Object> page = page(i, 20);
//				PageInfo<Object> page = cacheBiz.recommendListPage(i, 20);
                List<Object> list = page.getList();
                for (int j = 0; j < list.size(); j++) {
                    if (list.get(j) instanceof NewsVo) {
                        NewsVo n = (NewsVo) list.get(j);
                        if (newsId.equals(n.getNewsId())) {
                            pageNum = i;

                            n.setBaseLike(newsVo.getBaseLike());
                            n.setLikeNum(newsVo.getLikeNum());
                            n.setLike(format(newsVo.getBaseLike() + newsVo.getLikeNum()));

                            n.setBasePlay(newsVo.getBasePlay());
                            n.setPlayNum(newsVo.getPlayNum());
                            n.setPlay(format(newsVo.getBasePlay() + newsVo.getPlayNum()));
                            newList = list;
                            newPage = page;
                            newPage.setList(newList);
                            String key = pageNum + "." + 20;
                            String redisKey = "r::page." + key;
                            redisUtils.set(redisKey, newPage);
                            break;
                        }
                    }
                }
            }

//			@SuppressWarnings("unchecked")
//			LoadingCache<Object,PageInfo<Object>> bean = SpringBeanUtils.getBean("recommendListCache", LoadingCache.class);
//			bean.put(key, newPage);
        }
    }


    public static String format(Integer count) {
        if (count < 10000) {
            return String.valueOf(count);
        }
        if (count % 10000 == 0) {
            return count / 10000 + "w";
        }
        double c = Double.valueOf(count + ".0");
        return String.format("%.1f", c / 10000) + "w";
    }
}
